<template>
	<view class="content-user out-padding">
		<view style="background-color: rgba(89, 159, 221, 0.1);padding: 30upx;border-radius: 20upx;display: inline-block;margin-top: 5vh;flex: 1;height: 1200upx;">
			<view style="margin: auto;">
				<view style="padding: 0 20upx;">
					<u-form :model="userInfo" ref="uForm">
						<u-form-item :label-style="labelStyle" required label-width="200" label="证件类型" prop="idType">
							<u-input class="input-style" @click="show = true" type="select" placeholder="请选择证件类型" v-model="userInfo.idType.label"/>
							<u-select safe-area-inset-bottom mode="single-column" v-model="show" :list="list" @confirm="confirm"></u-select>
						</u-form-item>
						<u-form-item :label-style="labelStyle" required label-width="200" label="姓名" prop="name">
							<u-input class="input-style" v-model="userInfo.name" />
						</u-form-item>
						<u-form-item :label-style="labelStyle" required label-width="200" label="证件号码" prop="idCode">
							<u-input class="input-style" v-model="userInfo.idCode" />
						</u-form-item>
					</u-form>
				</view>
				<view class="content-image-box">
					<view style="display: flex;align-items: center;">
						<view style="color: #FFFFFF;flex: .5;">
							<text style="color: #fa3534;">*</text>
							照片
						</view>
						<view>
							<view v-if="!userInfo.base64Img" class="selected-photo photo-image">
								<view style="text-align: center;" @click="selectedPhoto">
									<u-icon name="plus" size="80" color="#ffffff"></u-icon>
									<view class="hint-text">请上传照片</view>
								</view>
							</view>
							<view v-else @click="selectedPhoto" class="selected-photo">
								<image class="show-image" :src="userInfo.base64Img"></image>
							</view>
							<view v-if="userInfo.base64Img" style="display: flex;align-items: center;width: 400upx;margin: 50upx 0;">
								<view style="margin-right: auto;">
									<u-icon @click="detail(resImg,'right')" size="64" color="#fff" name="arrow-left-double"></u-icon>
								</view>
								<view style="color: #FFFFFF;">调整</view>
								<view style="margin-left: auto;">
									<u-icon @click="detail(resImg,'left')" size="64" color="#fff" name="arrow-right-double"></u-icon>
								</view>
							</view>
						</view>
					</view>
					<u-alert-tips style="margin-top: 20upx;" :type="descriptionType" :description="description"></u-alert-tips>
					<u-button throttle-time="3000" :disabled="loadingShow" :loading="loadingShow" class="submit-btn" style="margin-top: 50upx;" type="warning" @click="submit">开始上传</u-button>
				</view>
			</view>
		</view>
		<w-compress ref='wCompress' />
	</view>
</template>

<script>
	import { pathToBase64 } from 'js_sdk/mmmm-image-tools/index.js';
	import WCompress from '@/components/w-compress/w-compress.vue';
	const EXIF = require('../../static/exif-js.js');
	export default {
		components: {
			WCompress
		},
		data() {
			return {
				resImg:'',
				labelStyle:{
					color: '#ffffff'
				},
				loadingShow: false, // 按钮加载
				show: false,//选择显示
				list:[ // 选择数据列表
					{ value: 'ID_CARD', label: '身份证' },
					{ value: 'OTHERS', label: '其他' }
				],
				descriptionType: "warning",
				description: '*请注意上传照片为单人正面大头照，保持人脸为正方向、不要侧脸、低头或者多人。',
				userInfo:{
					base64Img: '',
					name: '', // 姓名
					idCode: '', // 身份证号
					idType:{
						value: 'ID_CARD',
						label: '身份证'
					},
				},
				tagObj:{},
				params:{},
				rules: {
					name: [
						{ 
							required: true, 
							message: '请输入姓名', 
							// 可以单个或者同时写两个触发验证方式 
							trigger: ['change','blur'],
						}
					],
					idCode: [
						{
							required: true, 
							message: '请输入证件号码',
							// 可以单个或者同时写两个触发验证方式 
							trigger: ['change','blur'],
						}
					],
				}
			}
		},
		onLoad() {
			// 查询当先项目标签
			this.getTag();
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			// 选择上传照片
			selectedPhoto() {
				let _this = this;
				uni.chooseImage({
				    count: 1, //默认9
				    success: function (res) {
						if(res.errMsg === 'chooseImage:ok') {
							_this.resImg = res.tempFilePaths[0]//这就是要的blod
							_this.detail(_this.resImg)
						}
				    }
				});
			},
			// 证件类型选择确认回调
			confirm(item) {
				this.userInfo.idType = item[0];
			},
			// 查询标签
			getTag() {
				uni.showLoading({ title: '加载中' });
				this.$api._getTag()
					.then(res => {
						console.log(res);
						uni.hideLoading();
						if(!res.data.success) return uni.showToast({ title: '接口异常，请联系管理员', icon:"none", duration: 2000 });
						if(res.data.success) {
							let tagId = [];
							if(res.data.result&&res.data.result.id) {
								let tagNameList = res.data.result.tagName;
								tagNameList.forEach(v => {
									tagId.push(v.tagId);
								})
							}
							res.data.result['tagId'] = tagId;
							this.tagObj = res.data.result;
						}
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
						uni.showToast({ title: '接口异常，请联系管理员', icon:"none", duration: 2000 });
					})
			},
			// 提交
			submit() {
				if(!this.userInfo.base64Img) return uni.showToast({ icon:"none", title: '请上传照片', duration: 2000 });
				if(!this.userInfo.idType || !this.userInfo.idType.value) return uni.showToast({ icon:"none", title: '请选择证照类型', duration: 2000 });
					this.$refs.uForm.validate(valid => {
						if (valid) {
							uni.showLoading({
							    title: '信息验证中'
							});
							this.loadingShow = true;
							this.searchBlack(this.userInfo.idCode);
						} else {
							console.log('验证失败');
						}
					});
			},
			// 根据证件号查询是否在黑名单里
			searchBlack(code) {
				let loginToken = uni.getStorageSync('loginToken');
				this.$api._searchBlack(code,this.tagObj.projectType)
					.then(res => {
						console.log(res);
						if(res.statusCode == 200) {
							if(res.data && res.data.success == false) {
								let params = {
									idCode: this.userInfo.idCode,
									idType: this.userInfo.idType.value,
								};
								this.checkBill(params);
							}else{
								uni.hideLoading();
								uni.showToast({ title: '无效的证票', icon:"none", duration: 2000 });
								this.loadingShow = false;
							}
						}else {
							uni.hideLoading();
							uni.showToast({ title: '内部异常', icon:"none", duration: 2000 });
							this.loadingShow = false;
						}
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
						uni.showToast({ title: '无效的证票', icon:"none", duration: 2000 });
						this.loadingShow = false;
					})
			},
			// 检验观众票是否存在 API
			checkBill(params) {
				this.$api._searchWhite(params.idCode,this.tagObj.projectType)
					.then(res => {
						console.log(res);
						if(res.statusCode == 200) {
							if(res.data&&res.data.success) {
								if(params.idType == "ID_CARD") {
									let DATA = {
										name: this.userInfo.name,
										idCardNumber: this.userInfo.idCode,
										image: this.userInfo.base64Img.split(",")[1],//去掉base64前缀
									}
									this.faceVerify(DATA,params);
								}else{
									let DATA = {
										... params,
										avatar: this.userInfo.base64Img.split(",")[1],
									}
									this.createStaff(DATA);
								}
								
							}else{
								uni.hideLoading();
								uni.showToast({ title: '不存在此观众票', icon:"none", duration: 2000 });
								this.loadingShow = false;
							}
						}else {
							uni.hideLoading();
							uni.showToast({ title: '系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
							this.loadingShow = false;
						}
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
						uni.showToast({ title: 'error,系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
						this.loadingShow = false;
					})
			},
			//三合一验证 API
			faceVerify(data,params) {
				this.$api._personVerify(data)
					.then(res => {
						console.log(res);
						if(res.statusCode == 200) {
							if(res.data && res.data.result) {
								let result = res.data.result;
								console.log(result);
								if(!result.result) {
									uni.showToast({ title: result.error_msg||'信息有误', icon:"none", duration: 2000 });
									uni.hideLoading();
									this.loadingShow = false;
									return ;
								}
								if(result.result.score > 70) {
									let DATA = {
										... params,
										avatar: this.userInfo.base64Img.split(",")[1],
									};
									this.createStaff(DATA);
								}else{
									uni.showToast({ title: '人脸相似度过低', icon:"none", duration: 2000 });
									uni.hideLoading();
									this.loadingShow = false;
								}
							}else{
								uni.hideLoading();
								uni.showToast({ title: '姓名、证件号、人脸不匹配', icon:"none", duration: 2000 });
								this.loadingShow = false;
							}
						}else {
							uni.hideLoading();
							uni.showToast({ title: '系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
							this.loadingShow = false;
						}
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
						uni.showToast({ title: 'error,系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
						this.loadingShow = false;
					})
			},
			
			// 新增加非身份证人员 API
			createStaff(params) {
				let DATA = {
				  "staff_list": [
					{
					  "face_image_content_list": [params.avatar],
					  "tag_id_list": [...this.tagObj['tagId']],
					  "person_information": {
						"id": params.idCode + "," + new Date().getTime(),
						"name": this.userInfo.name,
						"remark": params.idCode,
					  }
					}
				  ]
				}
				this.$api._addStaffs(DATA)
					.then(res => {
						console.log(res);
						uni.hideLoading();
						this.loadingShow = false;
						if(res.statusCode == 200) {
							if(res.data && res.data.code == 200) {
								if(res.data.result && res.data.result.rtn == 0) {
									uni.showToast({ title: '录入成功！', duration: 2000 });
									getApp().globalData.userInfo = JSON.parse(JSON.stringify(this.userInfo));
									uni.navigateTo({
										url:"../electronicCertificate/electronicCertificate"
									})
									this.submitHistory({... params,name: this.userInfo.name})
									this.initUser();
								}else{
									uni.showToast({ title: res.data.result.message||'添加失败，信息有误', icon:"none", duration: 2000 });
								}
								
							}else{
								uni.showToast({ title: '证件类型或证件号错误', icon:"none", duration: 2000 });
							}
						}else {
							uni.showToast({ title: '系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
						}
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
						this.loadingShow = false;
						uni.showToast({ title: 'error,系统内部异常,请联系管理员！', icon:"none", duration: 2000 });
					})
			},
			initUser() {
				this.userInfo = {
					base64Img: '',
					name: '', // 姓名
					idCode: '', // 身份证号
					idType:{
						value: 'ID_CARD',
						label: '身份证'
					},
				};
			},
			// 提交记录
			submitHistory(params) {
				console.log(params)
				let loginToken = uni.getStorageSync('loginToken');
				let Data = {
					avatar: params.avatar,
					idCode: params.idCode,
					name: params.name,
					address: this.address,
					cardType: params.idType,
					type: this.tagObj.projectType
				}
				this.$api._saveRegister(Data)
					.then(res => {
						console.log(res);
						if(res.statusCode == 200) {
							if(res.data && res.data.data) {
								console.log("成功提交")
							}else{
								console.log("失败1")
							}
						}else {
							console.log("失败2")
						}
					})
					.catch(err => {
						console.log(err);
						console.log("失败3")
					})
			},
			
			//url 就是上面获取到的blod
			async detail(url,direction) {
				 let maxWidth = 500;  
				 let Orientation = 1;  
				 //获取图片META信息  
				 await this.getImageTag(url, 'Orientation', function(e) {
					 console.log('获取图片META信息',e);
					 if(e != undefined) Orientation = e;  
				 })
				 var img = null;  
				 var canvas = null;
				 let baseStr = ''; 
				 await this.comprossImage(url, maxWidth, function(e) {
					 console.log(e)
					 img = e.img;  
					 canvas = e.canvas;  
				 })
				 if(direction) {
					 if(direction == "left") {
						 baseStr = this.rotateImg(img,'left',canvas);  
					 }else{
						 baseStr = this.rotateImg(img,'right',canvas);  
					 }
				 }else{
					 console.log(Orientation,"Orientation");
					 baseStr = this.rotateImg(img,'',canvas);
					//  //如果方向角不为1，都需要进行旋转  
					//  switch(Orientation){
					// 	 case 6://需要顺时针（向右）90度旋转  
					// 		 baseStr = this.rotateImg(img,'right',canvas);  
					// 		 break;  
					// 	 case 8://需要逆时针（向左）90度旋转   
					// 		 baseStr = this.rotateImg(img,'left',canvas);  
					// 		 break;  
				 
					// 	 case 3://需要180度旋转 转两次  
					// 		 baseStr = this.rotateImg(img,'right',canvas, 2);  
					// 		 break;  
					// 	 default:  
					// 		 baseStr = this.rotateImg(img,'',canvas);
					// 		 break;  
					//  }
				 }
				 this.userInfo.base64Img = baseStr;
				 this.resImg = this.translateBase64ImgToBlob(baseStr)
				 
				// console.log(baseStr)
				// this.uploadImg(baseStr)//图片上传到服务器的方法
		 },
		 //-------------------------------直接粘贴的三个方法
			 async comprossImage(imgSrc, maxWidth, func){
				 console.log(imgSrc)
				 if(!imgSrc) return 0;  
				 return new Promise((resolve, reject) => { 
					 uni.getImageInfo({  
						 src: imgSrc,  
						 success(res) {
							 let img = new Image();  
							 img.src = res.path;  
							 console.log(img)  
			 
							 let canvas = document.createElement('canvas');  
			 
							 let obj = new Object();
							 obj.img = img;  
							 obj.canvas = canvas;  
							 resolve(func(obj));  
						 }  
					 });  
				 })
			},
			  /**  
			  * @desc 获取图片信息，使用exif.js库，具体用法请在github中搜索  
			  * @param {Object} file 上传的图片文件  
			  * @param {String} tag 需要获取的信息 例如：'Orientation'旋转信息  
			  * @return {Promise<Any>} 读取是个异步操作，返回指定的图片信息  
			  */  
			getImageTag(file, tag, suc){
				console.log(file)
				console.log(tag)
				console.log(suc)
				 if (!file) return 0;  
				 return new Promise((resolve, reject) => {
					 /* eslint-disable func-names */  
					 // 箭头函数会修改this，所以这里不能用箭头函数  
					 let imgObj = new Image()  
					 imgObj.src = file  
					 console.log(imgObj)  
					 uni.getImageInfo({  
						 src: file,  
						 success(res) {
							 console.log(res)
							 EXIF.getData(imgObj, function () {
								 EXIF.getAllTags(this);    
								 let or = EXIF.getTag(this,'Orientation');//这个Orientation 就是我们判断需不需要旋转的值了，有1、3、6、8  
								 console.log(or)
								 resolve(suc(or))  
							 });  
						 }  
					 })  
				 });  
			 },
				 
			 rotateImg(img, direction, canvas, times = 1) {
				 console.log('开始旋转')  
				 //最小与最大旋转方向，图片旋转4次后回到原方向    
				 var min_step = 0;    
				 var max_step = 3;
				  console.log(img)
				 if (img == null)return;    
			 
				 //img的高度和宽度不能在img元素隐藏后获取，否则会出错    
				 var height = img.height;    
				 var width = img.width;    
				 let maxWidth = 500;  
				 let canvasWidth = width; //图片原始长宽  
				 let canvasHeight = height;  
				 let base = canvasWidth/canvasHeight;  
				 console.log(maxWidth);  
				 if(canvasWidth > maxWidth){  
					 canvasWidth = maxWidth;  
					 canvasHeight = Math.floor(canvasWidth/base);  
				 }  
				 width = canvasWidth;  
				 height = canvasHeight;  
				 var step = 0;    
			 
				 if (step == null) {    
				   step = min_step;    
				 }    
			 
				 if (direction == 'right') {    
				   step += times;    
				   //旋转到原位置，即超过最大值    
				   step > max_step && (step = min_step);    
				 } else if(direction == 'left'){    
				   step -= times;    
				   step < min_step && (step = max_step);    
				 } else {    //不旋转  
					 step = 0;  
				 }  
			 
				 //旋转角度以弧度值为参数    
				 var degree = step * 90 * Math.PI / 180;    
				 var ctx = canvas.getContext('2d');    
				 console.log(degree)  
				 console.log(step)  
				 switch (step) {
				   case 1:    
					 console.log('右旋转 90度')  
					 canvas.width = height;    
					 canvas.height = width;    
					 ctx.rotate(degree);    
					 ctx.drawImage(img, 0, -height, width, height);    
					 break;    
				   case 2:    
					 //console.log('旋转 180度')  
					 canvas.width = width;    
					 canvas.height = height;    
					 ctx.rotate(degree);    
					 ctx.drawImage(img, -width, -height, width, height);    
					 break;    
				   case 3:    
					 console.log('左旋转 90度')  
					 canvas.width = height;    
					 canvas.height = width;    
					 ctx.rotate(degree);    
					 ctx.drawImage(img, -width, 0, width, height);  
					 break;    
				   default:  //不旋转  
					 canvas.width = width;  
					 canvas.height = height;  
					 ctx.drawImage(img, 0, 0, width, height);  
					 break;  
				 }  
			 
				 let baseStr = canvas.toDataURL("image/jpeg");
				 return baseStr;  
			},
				 //-----------------------------------------------结束
				 
				 
			 /**
			  * Base64转Blob
			  * @param base64 String base64格式字符串
			  * @param contentType String blob对象的文件类型，如："image/jpg"
			  */
			  translateBase64ImgToBlob(base64,contentType = "image/jpg"){
				  var arr = base64.split(',')  //去掉base64格式图片的头部
				  var bstr = atob(arr[1])   //atob()方法将数据解码
				  var leng = bstr.length
				  var u8arr = new Uint8Array(leng)
				  while(leng--){
					 u8arr[leng] =  bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
				  }
				  var blob = new Blob([u8arr],{type:contentType})
				  return URL.createObjectURL(blob )  //创建URL, 
			  }
		},
	}
</script>

<style scoped lang="scss">
.content-user{
	background-color: rgba(0,0,0,.9);
	height: 100vh;
	display: flex;
	.content-image-box{
		padding-top: 10upx;
		height: 440upx;
		.selected-photo{
			width: 250upx;
			height: 250upx;
			border-radius: 10upx;
			border: 2upx solid #C0C0C0;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: auto;
			margin-top: 30upx;
			.hint-text{
				color: #FFFFFF;
				font-size: 32upx;
				z-index: 9;
				position: relative;
				margin-top: 10upx;
			}
			.show-image{
				width: 250upx;
				height: 250upx;
				border-radius: 10upx;
			}
		}
		.photo-image{
			position: relative;
			background: url(../../static/user.png) no-repeat center;
			background-size: 80% 80%;
			background-position: center 20upx;
		}
		.photo-image:before{
			content: '';
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			background-color: rgba(0,0,0,.5);
			border-radius: 10upx;
		}
	}
}
.input-style /deep/ input{
	color: orange;
}
</style>
